package cn.com.fig.service;

import java.util.List;
import java.util.Map;

import cn.com.fig.dao.DepartmentMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mysql.jdbc.StringUtils;

import cn.com.fig.common.PaginationReqParam;
import cn.com.fig.common.PaginationResponse;
import cn.com.fig.common.ReplyMsg;

/**
 * @author 刘文成
 *组织机构管理
 */
@Service
public class DepartmentService {
	@Autowired
	private DepartmentMapper dao;
	
	/**
	 * 分页查询
	 * @param reqParam
	 * @param sysId
	 * @param privilegeName
	 * @return
	 */
	public PaginationResponse<Map<String,Object>> listDepartment(PaginationReqParam reqParam){
		if(reqParam.isNeedSplitPage())
			PageHelper.startPage(reqParam.getStartIndex(), reqParam.getRows());		
	
		List<Map<String,Object>> list = dao.listDepartment();
		PageInfo<Map<String, Object>> page = new PageInfo<Map<String, Object>>(list);
		
		PaginationResponse<Map<String,Object>> res = new PaginationResponse<Map<String,Object>>();
		res.setNumPerPage(reqParam.getRows());
		res.setRows(list);
		res.setTotalRows(page.getTotal());
		return res;
	}

	/**
	 * 根据privillegeId判断是否存在主键，若有主键则更新，否则新增
	 * @param tradeSys
	 * @return
	 */
	public ReplyMsg save(Map<String,Object> department){
		int ret = 0;
		ReplyMsg msg = new ReplyMsg();
		String departId = department.get("departId") == null ?null : department.get("departId").toString();
		if(StringUtils.isNullOrEmpty(departId)){
			msg.setRetCode("-1");
			msg.setRetMsg("请填写机构编号");
			return msg;
		}
		String parentId = (String)department.get("parentId");
		if(parentId != null && "".equals(parentId.trim())){
			department.put("parentId", null);
		}
		String insertMark = department.get("insertMark").toString();//1插入；0更新
		if(insertMark == null || insertMark.equals("1")){		
			ret = dao.insert(department);
		}else{
			ret = dao.update(department);
		}
		if(ret <1){
			msg.setRetCode("-1");
			msg.setRetMsg("保存业务系统数据失败！");
		}
		return msg;
	}
	
	public ReplyMsg del(String departId){
		int ret = 0;
		ReplyMsg msg = new ReplyMsg();
		
		if(StringUtils.isNullOrEmpty(departId)){
			msg.setRetCode("-1");
			msg.setRetMsg("请选择要删除的机构");
			return msg;
		}
		
		ret = dao.delete(departId);
		if(ret <1){
			msg.setRetCode("-1");
			msg.setRetMsg("删除组织机构数据失败！");
		}
		return msg;
	}
}
